import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xmshop/app/models/user_model.dart';
import 'package:xmshop/app/modules/address/addressList/controllers/address_list_controller.dart';
import 'package:xmshop/app/services/signService.dart';
import '../../../../services/httpsClient.dart';
import '../../../../services/userService.dart';

class AddressAddController extends GetxController {
  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  AddressListController listController = Get.find<AddressListController>();
  RxString area = "".obs;
  HttpsClient httpsClient = HttpsClient();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    super.onClose();
    listController.getAddressList();
  }

  setArea(String str) {
    area.value = str;
    update();
  }

  doAddAddress() async {
    // 获取用户信息
    var userInfoMap = await UserService.getUserInfo();
    if (userInfoMap != null) {
      UserModel userInfo =
          UserModel.fromJson(userInfoMap as Map<String, dynamic>);

      if (nameController.text.length < 2) {
        Get.snackbar("提示信息", "请把姓名填写完整");
      } else if (!GetUtils.isPhoneNumber(phoneController.text) ||
          phoneController.text.length != 11) {
        Get.snackbar("提示信息", "手机号不合法");
      } else if (area.value.length < 2) {
        Get.snackbar("提示信息", "请选择地区");
      } else if (addressController.text.length < 2) {
        Get.snackbar("提示信息", "请填写详细的地址");
      } else {
        Map tempJson = {
          "uid": userInfo.sId,
          "name": nameController.text,
          "phone": phoneController.text,
          "address": "${area.value} ${addressController.text}"
        };

        // 获取签名
        String sign = SignService.getSign({
          ...tempJson, // 合并对象
          "salt": userInfo.salt // 登录成功后服务器返回的salt 私钥
        });

        var response = await httpsClient
            .post("/api/addAddress", data: {...tempJson, "sign": sign});
        if (response.data["success"]) {
          // 新增成功
          Get.back();
        } else {
          Get.snackbar("提示信息", response.data["message"]);
        }
      }
    }
  }
}
